package com.xiaouyudeguang.common.utils;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.HashMap;
import java.util.Map;

public class SpelUtils {

    private static final ExpressionParser parser = new SpelExpressionParser();

    public static void main(String[] args) {
        String sql = "select * from sys_user";
        String expressionString = "\"#{#name}\" == null || \"#{#name}\".equals(\"\")? \"\" : \" and name like '%#{#name}%'";
        Map<String, Object> map = new HashMap<>();
        map.put("name", "赵");
        System.out.println(sql + parseExpression(expressionString, map));
    }

    public static String parseExpression(String expressionString, String name, String value) {
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable(name, value);
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(expressionString, new TemplateParserContext());
        expressionString = expression.getValue(context, String.class);
        return StringUtils.isBlank(expressionString) ? null : parser.parseExpression(expressionString).getValue(String.class);
    }

    public static String parseExpression(String expressionString, Map<String, Object> map) {
        EvaluationContext context = new StandardEvaluationContext();
        map.forEach(context::setVariable);
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(expressionString, new TemplateParserContext());
        expressionString = expression.getValue(context, String.class);
        return StringUtils.isBlank(expressionString) ? null : parser.parseExpression(expressionString).getValue(String.class);
    }
}
